from PyQt5.QtWidgets import QMainWindow, QDialog, QDesktopWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QTimer

# 导入窗体内容
from design.loginWindow import *

from common.logger import logger
from common.retcode import RetCode
from common.utils import center_window_on_screen
from api.token import get_token
from api.login import LoginAction
from windows.main import *
from windows.captcha import *

# 创建loginWindow类并传入Ui_MainWindow
class LoginWin(QMainWindow, Ui_LoginWindow):
	def __init__(self, sess_wp, parent=None):
		super(LoginWin, self).__init__(parent)
		self.setupUi(self)
		center_window_on_screen(self)

		self._sess_wp = sess_wp
		self._main_win = None
		self._captcha_dlg = None
		
		self.pushButtonSubmit.clicked.connect(self.onClickedLoginSubmit)
		self.comboBoxUsername.currentIndexChanged.connect(self.onComboBoxUsernameChanged)
		self.reset()

	def reset(self):
		self.labelLoginResultIcon.hide()
		self.labelLoginResultText.hide()
		self.pushButtonSubmit.setEnabled(True)

		lastUsername, lastPassword = self._sess_wp.get_last_credential()
		idx = 0
		self.comboBoxUsername.clear()
		for username in self._sess_wp.get_all_usernames():
			self.comboBoxUsername.insertItem(idx, username)
			idx += 1
		self.comboBoxUsername.setEditText(lastUsername)
		self.lineEditPassword.setText(lastPassword)

	def onClickedLoginSubmit(self):
		self.labelLoginResultIcon.setPixmap(QPixmap(':/icon/icons/waiting.png'))
		self.labelLoginResultText.setText('尝试快速登录...')
		self.labelLoginResultIcon.show()
		self.labelLoginResultText.show()
		self.pushButtonSubmit.setEnabled(False)

		QTimer.singleShot(0, self.doQuickLogin)

	def onComboBoxUsernameChanged(self, index):
		username = self.comboBoxUsername.itemText(index)
		password = self._sess_wp.get_password_cached(username)
		self.lineEditPassword.setText(password)

	def handleCaptcha(self, img_data):
		if not self._captcha_dlg:
			self._captcha_dlg = CaptchaDlg()

		self._captcha_dlg.reset(self._sess_wp, img_data)
		ret_code = self._captcha_dlg.exec_()
		# print(f'ret_code = {ret_code}')

		if ret_code == QDialog.Accepted:
			return self._captcha_dlg.get_captcha_text()
		else:
			return None

	def doQuickLogin(self):
		username = self.comboBoxUsername.currentText()
		password = self.lineEditPassword.text()

		# 先尝试 login_by_cookie
		if self._sess_wp.set_session_from_config(username):
			login_action = LoginAction(self._sess_wp)
			code = login_action.login_by_cookie()
			if code == RetCode.SUCCESS:
				self._sess_wp.set_last_username(username)
				
				self.labelLoginResultIcon.setPixmap(QPixmap(':/icon/icons/ok.png'))
				self.labelLoginResultText.setText(f'登录成功')
				QTimer.singleShot(1000, self.showMainWin)
				return

		self.labelLoginResultText.setText('正在登录...')
		QTimer.singleShot(0, self.doLogin)

	def doLogin(self):
		username = self.comboBoxUsername.currentText()
		password = self.lineEditPassword.text()
		print(username, password)

		login_action = LoginAction(self._sess_wp)
		login_action.set_captcha_handler(self.handleCaptcha)
		code = login_action.login(username, password)
		
		if code != RetCode.SUCCESS:
			self.labelLoginResultIcon.setPixmap(QPixmap(':/icon/icons/failed.png'))
			self.labelLoginResultText.setText(f'登录失败: {code}')
			self.pushButtonSubmit.setEnabled(True)
		else:
			self.labelLoginResultText.setText(f'正在获取访问凭证...')

			QTimer.singleShot(0, self.doFetchToken)

	def doFetchToken(self):
		username = self.comboBoxUsername.currentText()
		password = self.lineEditPassword.text()
		code, token = get_token(username, password)
		if code != RetCode.SUCCESS:
			self.labelLoginResultIcon.setPixmap(QPixmap(':/icon/icons/failed.png'))
			self.labelLoginResultText.setText(f'获取访问凭证失败: {code}')
			self.pushButtonSubmit.setEnabled(True)
		else:
			self.labelLoginResultIcon.setPixmap(QPixmap(':/icon/icons/ok.png'))
			self.labelLoginResultText.setText(f'登录成功')

			print(token)
			self._sess_wp.set_session(*token)

			# 保存登录信息
			self._sess_wp.save_login_info(username, password)

			QTimer.singleShot(1000, self.showMainWin)

	def showMainWin(self):
		self.hide()
		if not self._main_win:
			self._main_win = MainWin(login_win=self)
		self._main_win.show()